#include <muduo/net/Buffer.h>
#include <muduo/net/EventLoop.h>
#include <muduo/net/TcpClient.h>
#include <muduo/net/TcpConnection.h>
#include <muduo/base/CountDownLatch.h>
#include <muduo/net/EventLoopThread.h>
#include <iostream>
#include <string>

class DictClient
{
public:
    DictClient(const std::string& sip, int port)
        :_client(_baseloop, muduo::net::InetAddress("0.0.0.0", port), "DictServer")
        , _downlatch(1)
        , _baseloop(_loopthread.startLoop()) // 创建线程自动监控
    {
        //设置事件回调
        _client.setConnectionCallback(std::bind(&DictClient::onConnection, this, std::placeholders::_1));
        _client.setMessageCallback(
            std::bind(&DictClient::onMessage, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));

        //连接
        _client.connect();
        _downlatch.wait();//阻塞

        //开始事件监控
        //_baseloop.loop();
        //不能直接监控，会死循环，无法发送数据，要创建一个线程进行监控
    }

    bool send(const std::string& msg)
    {
        if(_conn->connected())
        {
            _conn->send(msg);
            
            return true;
        }
        std::cout << "连接断开" << std::endl;
        return false;
    }

private:
    void onConnection(const muduo::net::TcpConnectionPtr& conn)
    {
        if(conn->connected()){
            std::cout << "连接建立" << std::endl;
            _downlatch.countDown(); // 计数--，为0唤醒
            _conn = conn;
        }
            
        else{
            std::cout << "连接断开" << std::endl;
            _conn.reset();
        }
    }

    void onMessage(const muduo::net::TcpConnectionPtr& conn, muduo::net::Buffer* buff, muduo::Timestamp)
    {
        std::string ret = buff->retrieveAllAsString();
        std::cout << ret << std::endl;
    }

    muduo::net::TcpConnectionPtr _conn;
    muduo::CountDownLatch _downlatch;
    muduo::net::EventLoopThread _loopthread;
    muduo::net::EventLoop* _baseloop;
    muduo::net::TcpClient _client;
};

int main()
{
    DictClient client("127.0.0.1", 8080);
    while(true)
    {
        std::string msg;
        std::cin >> msg;
        client.send(msg);
    }
    return 0;
}